<template>
	<div>
		<el-dialog :title="options.title" v-model="isShowDialog" width="769px">
			<el-row :gutter="5">
				<el-col :xs="16" :sm="16" :md="16" :lg="16" :xl="16" class="mb20" style="height: 500px;">
					<div class="docs-demo">
						<div class="img-container" v-html="rawHtml">
						</div>
					</div>
				</el-col>
				<el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8" class="mb10"
					style="text-align: center;height: 500px;display:flex;align-items: center;">
					<div style="width: 100%;">
						<el-row>
							<el-col class="mb10" style="text-align: left;">
								建议图片 宽大于{{options.cropperSize.width?options.cropperSize.width:'*'}}  高大于 {{ options.cropperSize.height?options.cropperSize.height:'*' }}
							</el-col>

						</el-row>
						<el-row>
							<el-col class="mb10" style="text-align: left;">
								<div class="img-preview preview-lg"></div>

							</el-col>
							<el-col class="mb10" style="text-align: left;">
								<div class="img-preview preview-md"></div>
								<div class="img-preview preview-sm"></div>
								<div class="img-preview preview-xs"></div>
							</el-col>


						</el-row>
						<el-row>
							<el-col class="mb10" style="text-align: left;">
								<label title="选择上传图片" for="inputImage" class="el-button el-button--success ">
									<el-icon>
										<Upload />
									</el-icon>
									<input type="file" class="sr-only" id="inputImage" name="file" accept="image/*"
										@change="inputImagechange" multiple />
								</label>
								<el-button type="success" @click="cropper.zoom(0.1)">
									<el-icon>
										<ZoomIn />
									</el-icon>
								</el-button>
								<el-button type="success" @click="cropper.zoom(-0.1)">
									<el-icon>
										<ZoomOut />
									</el-icon>
								</el-button>
								
							</el-col>
						</el-row>
						<el-row>
							<el-col class="mb10" style="text-align: left;">
							 
								<el-button type="success" @click="cropper.rotate(-45)">
									<el-icon>
										<RefreshLeft />
									</el-icon>
								</el-button>
								<el-button type="success" @click="cropper.rotate(45)">
									<el-icon>
										<RefreshRight />
									</el-icon>
								</el-button>
								
							</el-col>
						</el-row>
					</div>
				</el-col>
			</el-row>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">{{options.btnCancel}}</el-button>
					<el-button type="primary" @click="onSubmit" size="default" >{{options.btnUpload}}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
	import {
		reactive,
		toRefs,
		nextTick,
	} from 'vue';
	import Cropper from 'cropperjs';
	import 'cropperjs/dist/cropper.css';
	import {
		ZoomIn,
		Upload,
		ZoomOut,
		RefreshLeft,
		RefreshRight
	} from '@element-plus/icons-vue'

	import { Session } from '/@/utils/storage';
	import {
		ElMessage
	} from 'element-plus';
	export default {
		name: 'cropperUpload',
		components: {
			Upload,
			ZoomIn,
			ZoomOut,
			RefreshLeft,
			RefreshRight
		},
		setup() {
			const state = reactive({
				isShowDialog: false,
				cropper: null,
				rawHtml: '',
				ID: 0,
				options: {
					title: '上传图片',
					btnUpload: '上传图片',
					btnCancel: '取消',
					UploadAPI: (params: FormData) => {},
					callback: () => {},
					cropperSize: {
						width: 400,
						height: 400,
					},
					params: new FormData(),
					cropperopt: {
						aspectRatio: NaN,
						autoCropArea: 1,
						preview: '.img-preview',
						ready: function(e) {
							//console.log(e.type);
						},
						cropstart: function(e) {
							//console.log(e.type, e.detail.action);
						},
						cropmove: function(e) {
							//console.log(e.type, e.detail.action);
						},
						cropend: function(e) {
							//	console.log(e.type, e.detail.action);
						},
						crop: function(e) {
							// var data = e.detail;

							///console.log(e.type);

						},
						zoom: function(e) {
							//console.log(e.type, e.detail.ratio);
						}
					}
				}

			});
			// 打开弹窗
			const openDialog = (src: string, options: object) => {
				if (options) {
					for (let item in state.options) {
						if (item === 'cropperopt') {
						 
							for (let it in state.options[item]) {
								if (it==='aspectRatio' || options[item][it]) {
									state.options[item][it] = options[item][it];
								}
							}

						} else {
							if (options[item]) {
								state.options[item] = options[item];

							}

						}

					}
				}
				state.rawHtml = '<img src="' + src + '" alt=""  class="cropper-warp-left-img"/>';
				//console.log(state.rawHtml);
				state.isShowDialog = true;

				nextTick(() => {
					initCropper();
				});
			};
			// 关闭弹窗
			const closeDialog = () => {
				if (state.cropper) {
					state.cropper.destroy();
					state.cropper = null;
				}
				state.isShowDialog = false;
			};
			// 取消
			const onCancel = () => {

				closeDialog();
			};
			// 更换
			const onSubmit = () => {
				if (state.cropper) {
					let canvas = state.cropper.getCroppedCanvas(state.options.cropperSize);

					canvas.toBlob(function(blob) {
						state.options.params.append('file', blob, 'avatar.jpg');
						state.options.UploadAPI(state.options.params).then(async (response) => {
							//console.log(response)
							if (response.code === 0) {
								ElMessage.success(`${response.message}`);
									
								let userInfo = Session.get('userInfo')
								if(userInfo.Avatar!='') {
									let oldAvatar = userInfo.Avatar.split('/')
									oldAvatar[5] = response.result
									let newAvatar = oldAvatar.join('/')
									userInfo.Avatar = newAvatar
								}else {
									let newAvatar = "https://yunshangpin.oss-cn-shanghai.aliyuncs.com/avatar/users/" + response.result
									userInfo.Avatar = newAvatar
									console.log(newAvatar)
								}
								Session.set('userInfo', userInfo) 
				
								if (state.options.callback) {
									state.options.callback(userInfo);

								}
								closeDialog();
							}
						});

					}, "image/jpeg");
				}
				// state.cropperImgBase64 = state.cropper.getCroppedCanvas().toDataURL('image/jpeg');
			};
			// 初始化cropperjs图片裁剪
			const initCropper = () => {

				const letImg: any = document.querySelector('.cropper-warp-left-img');
				if (state.cropper) {
					state.cropper.destroy();
					state.cropper = null;
				}
				if(letImg){
				  state.cropper = new Cropper(letImg, state.options.cropperopt);
				}

			};
			const inputImagechange = (e) => {
				//console.log(e.target);
				var URL = window.URL || window.webkitURL;
				let self = e.target;
				var files = self.files;
				var file;
				if (files && files.length) {
					file = files[0];

					if (/^image\/\w+/.test(file.type)) {

						const image: any = document.querySelector('.cropper-warp-left-img');
						image.src = URL.createObjectURL(file);

						if (state.cropper) {
							state.cropper.destroy();
							state.cropper = null;
						}

						state.cropper = new Cropper(image, state.options.cropperopt);
						self.value = null;
					}
				}
			}

			return {
				openDialog,
				closeDialog,
				onCancel,
				onSubmit,
				initCropper,
				inputImagechange,
				...toRefs(state),
			};
		},
	};
</script>

<style scoped lang="scss">
	.btn {
		padding-left: 0.75rem;
		padding-right: 0.75rem;
	}

	label.btn {
		margin-bottom: 0;
	}

	.d-flex>.btn {
		flex: 1;
	}

	.carbonads {
		border: 1px solid #ccc;
		border-radius: 0.25rem;
		font-size: 0.875rem;
		overflow: hidden;
		padding: 1rem;
	}

	.carbon-wrap {
		overflow: hidden;
	}

	.carbon-img {
		clear: left;
		display: block;
		float: left;
	}

	.carbon-text,
	.carbon-poweredby {
		display: block;
		margin-left: 140px;
	}

	.carbon-text,
	.carbon-text:hover,
	.carbon-text:focus {
		color: #fff;
		text-decoration: none;
	}

	.carbon-poweredby,
	.carbon-poweredby:hover,
	.carbon-poweredby:focus {
		color: #ddd;
		text-decoration: none;
	}

	@media (min-width: 768px) {
		.carbonads {
			float: right;
			margin-bottom: -1rem;
			margin-top: -1rem;
			max-width: 360px;
		}
	}

	.footer {
		font-size: 0.875rem;
	}

	.heart {
		color: #ddd;
		display: block;
		height: 2rem;
		line-height: 2rem;
		margin-bottom: 0;
		margin-top: 1rem;
		position: relative;
		text-align: center;
		width: 100%;
	}

	.heart:hover {
		color: #ff4136;
	}

	.heart::before {
		border-top: 1px solid #eee;
		content: " ";
		display: block;
		height: 0;
		left: 0;
		position: absolute;
		right: 0;
		top: 50%;
	}

	.heart::after {
		background-color: #fff;
		content: "♥";
		padding-left: 0.5rem;
		padding-right: 0.5rem;
		position: relative;
		z-index: 1;
	}

	.docs-demo {
		margin-bottom: 1rem;
		overflow: hidden;
		padding: 2px;
	}

	.img-container,
	.img-preview {
		background-color: #f7f7f7;
		text-align: center;
		width: 100%;
	}

	.img-container {
		max-height: 497px;
		min-height: 200px;
	}

	@media (min-width: 768px) {
		.img-container {
			min-height: 497px;
		}
	}

	.img-container>img {
		max-width: 100%;
	}

	.docs-preview {
		margin-right: -1rem;
	}

	.img-preview {
		float: left;
		margin-bottom: 0.5rem;
		margin-right: 0.5rem;
		overflow: hidden;
	}

	.img-preview>img {
		max-width: 100%;
	}

	.preview-lg {
		height: 13.5rem;
		width: 24rem;
	}

	.preview-md {
		height: 6.75rem;
		width: 12rem;
	}

	.preview-sm {
		height: 3.375rem;
		width: 6rem;
	}

	.preview-xs {
		height: 1.6875rem;
		margin-right: 0;
		width: 3rem;
	}

	.docs-data>.input-group {
		margin-bottom: 0.5rem;
	}

	.docs-data .input-group-prepend .input-group-text {
		min-width: 4rem;
	}

	.docs-data .input-group-append .input-group-text {
		min-width: 3rem;
	}

	.docs-buttons>.btn,
	.docs-buttons>.btn-group,
	.docs-buttons>.form-control {
		margin-bottom: 0.5rem;
		margin-right: 0.25rem;
	}

	.docs-toggles>.btn,
	.docs-toggles>.btn-group,
	.docs-toggles>.dropdown {
		margin-bottom: 0.5rem;
	}

	.docs-tooltip {
		display: block;
		margin: -0.5rem -0.75rem;
		padding: 0.5rem 0.75rem;
	}

	.docs-tooltip>.icon {
		margin: 0 -0.25rem;
		vertical-align: top;
	}

	.tooltip-inner {
		white-space: normal;
	}

	.btn-upload .tooltip-inner,
	.btn-toggle .tooltip-inner {
		white-space: nowrap;
	}

	.btn-toggle {
		padding: 0.5rem;
	}

	.btn-toggle>.docs-tooltip {
		margin: -0.5rem;
		padding: 0.5rem;
	}

	@media (max-width: 400px) {
		.btn-group-crop {
			margin-right: -1rem !important;
		}

		.btn-group-crop>.btn {
			padding-left: 0.5rem;
			padding-right: 0.5rem;
		}

		.btn-group-crop .docs-tooltip {
			margin-left: -0.5rem;
			margin-right: -0.5rem;
			padding-left: 0.5rem;
			padding-right: 0.5rem;
		}
	}

	.docs-options .dropdown-menu {
		width: 100%;
	}

	.docs-options .dropdown-menu>li {
		font-size: 0.875rem;
		padding: 0.125rem 1rem;
	}

	.docs-options .dropdown-menu .form-check-label {
		display: block;
	}

	.docs-cropped .modal-body {
		text-align: center;
	}

	.docs-cropped .modal-body>img,
	.docs-cropped .modal-body>canvas {
		max-width: 100%;
	}
</style>
